from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pytesseract
import cv2
import numpy as np
import re
import time
from selenium.webdriver.common.keys import Keys
# 初始化Chrome浏览器
driver = webdriver.Edge()

# 打开指定的网页
driver.get("https://cas.shengda.edu.cn/lyuapServer/login?service=http://shengda.fysso.chaoxing.com/sso/shengda")

# 设置显式等待
wait = WebDriverWait(driver, 15)

def login_with_captcha(driver, wait):
    try:
        # 等待验证码图片元素出现并截取验证码图片
        captcha_image = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="root"]/span/div[3]/div/div/div[1]/div/div/form/div[4]/div/div/span/div/div[2]/div/img')))
        captcha_image.screenshot('captcha.png')

        # 读取图像
        image = cv2.imread('captcha.png')

        # 转换为灰度图
        gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 使用自适应阈值进行二值化
        binary_image = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                            cv2.THRESH_BINARY, 11, 2)

        # 去噪（如果需要）
        binary_image = cv2.medianBlur(binary_image, 3)

        # 形态学操作（如果需要）
        kernel = np.ones((1, 1), np.uint8)
        binary_image = cv2.dilate(binary_image, kernel, iterations=1)

        # 使用 pytesseract 进行 OCR 识别
        captcha_text = pytesseract.image_to_string(binary_image, config='--psm 7 --oem 1 -c tessedit_char_whitelist=0123456789*+=')

        # 打印识别结果
        print("识别出的文本:", captcha_text)

        # 使用正则表达式提取数学表达式
        math_expression = re.search(r'(\d+)\s*([*×+])\s*(\d+)', captcha_text)

        if math_expression:
            # 提取数字并计算结果
            num1, operator, num2 = math_expression.groups()
            num1, num2 = int(num1), int(num2)
            # 根据符号计算结果
            if operator in ['*', '×']:
                result = num1 * num2
            elif operator in ['+']:
                result = num1 + num2
            print("识别出的数学表达式:", math_expression.group())
            print("计算结果:", result)
        else:
            print("未能识别出数学表达式")
            result = 1  # 如果未能识别出数学表达式，则输入1

        # 等待验证码输入框出现并输入验证码
        captcha_input = wait.until(EC.presence_of_element_located((By.ID, 'captcha')))
        captcha_input.clear()
        captcha_input.send_keys(str(result))

        # 等待登录按钮出现并点击
        login_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="root"]/span/div[3]/div/div/div[1]/div/div/form/div[5]/button[1]')))
        login_button.click()

        # 检查是否出现登录失败的弹窗
        try:
            wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[4]/div/div[2]/div/div[2]/div/div/div[2]/button')))
            return False  # 如果出现弹窗，返回False，重新尝试
        except TimeoutException:
            return True  # 如果没有出现弹窗，说明登录可能成功，返回True

    except TimeoutException:
        print("等待超时，请检查网络或页面加载情况。")
        return False
    except NoSuchElementException as e:
        print("元素未找到:", e)
        return False

# 输入账号密码
account_input = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/span/div[3]/div/div/div[1]/div/div/form/div[1]/div/div/span/span/input')))
account_input.send_keys("202405930226")

password_input = wait.until(EC.presence_of_element_located((By.ID, 'password')))
password_input.send_keys("KKbjbzbj.3")
print("账号密码输入结束")

# 尝试登录直到成功
login_successful = False
while not login_successful:
    login_successful = login_with_captcha(driver, wait)
    if not login_successful:
         # 关闭弹窗
        try:
            # 等待弹窗出现并点击确认按钮
            popup_button = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[4]/div/div[2]/div/div[2]/div/div/div[2]/button')))
            popup_button.click()
            print("登录失败，尝试关闭弹窗...")
            # 等待验证码输入框出现
            captcha_input = wait.until(EC.presence_of_element_located((By.ID, 'captcha')))
            captcha_input.send_keys(Keys.CONTROL, 'a')  # 全选
            captcha_input.send_keys(Keys.DELETE)  # 删除
        except NoSuchElementException:
            print("无法找到弹窗关闭区域")
        captcha_input = wait.until(EC.presence_of_element_located((By.ID, 'captcha')))
        captcha_input.send_keys("")

# 获取登录后的界面标题并输出
print("登录后的界面标题:", driver.title)

# 清理资源
driver.quit()
#time.sleep(5)